import axio from "../assets/axio.js";
export  const view_upload = {
  template: `
    <div id="view_upload">
      <header>   
        <div class="input_group">
          <input @change="processSelectedFiles($event)" type="file" multiple="multiple"
        accept="*.rar, *.zip, *.gif, *.jpeg, *.png, *.jpg, *.bmp "/>
        </div>
        <div class="button_group">
          <button @click="handleUpload('u')">send to Upload</button>&ensp;
          <button @click="handleUpload('d')">send to Download</button>   
        </div>
      </header>
      <hr>
      <table>
          <tr class="fileitem" v-for="(f,index) in file">
              <td class="filename">{{f.name}}</td>
              <td class="filesize">{{computeSize(f.size)}}</td>
              <td class="progress">
                  <progress min="0" max="100" :value="process[index]"></progress>
                  {{ process[index] }}%
              </td>
              <td class="option">
                  <button class="cancel" @click="handleCancel(index)" v-if="process[index]==0">取消</button>
                  <span class="target" v-if="process[index]!=0">{{target}}</span>
              </td>
          </tr>
      </table>
      <div class="note">
        <p v-if="file.length>0">* 上传中无法取消，请慎重选择文件</p>
        <p v-if="file.length>0">* 重新选择文件会覆盖之前的列表</p>
      </div>
    </div>

  `,
  name: "view_upload",
  data() {
    return {
      file: [],
      process: [],
      target: "[U]",
    };
  },
  computed: {
    computeSize: () => {
      return (size) => {
        let s = "B";
        if (size > 1024) {
          size /= 1024;
          s = "KB";
        }
        if (size > 1024) {
          size /= 1024;
          s = "MB";
        }
        if (size > 1024) {
          size /= 1024;
          s = "GB";
        }
        return size.toFixed(2) + s;
      };
    },
  },
  methods: {
    handleUpload(action = "u") {
      action == "u" ? (this.target = "[U]") : (this.target = "[D]");
      for (let i = 0; i < this.file.length; i++) {
        const formData = new FormData();
        formData.append("files", this.file[i]);
        axio
          .post("/fields/upload?t=" + action, formData, this, i)
          .then((response) => {
            console.log(response);
          });
      }
    },
    handleUpdateProcess(index, value) {
      this.process[index] = value;
    },
    processSelectedFiles(e) {
      this.file = e.target.files;
      this.process = [];
      for (let i = 0; i < this.file.length; i++) {
        this.process.push(0);
      }
      console.log(this.file);
      //重新选择会覆盖
    },
    handleCancel(index) {
      let t = [];
      for (let i = 0; i < this.file.length; i++) {
        if (i != index) {
          t.push(this.file[i]);
        }
      }
      this.file = t;
    },
  },
};

